var Promotion = {

    changeStatus:function(){
        var value = $("#status").val();
        if(value == 1){
            $("#totalDiv").show();
        }else{
            $("#totalDiv").hide();
        }
    },
    removeRestriction:function(id) {
        $("#"+id).css('display' , 'none');
        
    },
    addRestriction:function(){
        var selectResValue = $('#selectRestriction').val();
	    
        $('#restriction_'+ selectResValue).css('display' , '');
    
        $('#Restriction_error').empty();
        
    },
    addProductAction:function(){
        var selectAction = $("#selectAction").val();
		
        var unacceptedAction1 = 0;
        var unacceptedAction2 = 0;
        var unacceptedAction3 = 0;
        var unacceptedAction4 = 0;
        var unacceptedAction5 = 0;
        var unacceptedAction6 = 0;
        var unacceptedAction7 = 0;
        var unacceptedAction8 = 0;
        if(selectAction == 1 || selectAction == 4){
            unacceptedAction1 = 2;
            unacceptedAction2 = 5;
            unacceptedAction3 = 6;
        }else if(selectAction == 2 || selectAction == 5){
            unacceptedAction1 = 1;
            unacceptedAction2 = 4;
            unacceptedAction3 = 6;
        }else if(selectAction == 6){
            unacceptedAction1 = 1;
            unacceptedAction2 = 2;
            unacceptedAction3 = 4;
            unacceptedAction4 = 5;
        }
	 
        var addedActions = document.getElementsByName("pro_action_type[]");
        if (addedActions){
            var i = 0;
            for (i; i < addedActions.length; i++) {
                if (selectAction == addedActions[i].value) {
                    jAlert($('#promotionActionInfo1').val());
                    return;
                }
                if(addedActions[i].value == unacceptedAction1 || addedActions[i].value == unacceptedAction2|| addedActions[i].value == unacceptedAction3|| addedActions[i].value == unacceptedAction4){
                	jAlert($('#promotionActionInfo2').val());
                    return;
                }
            }
        }
		
		
		
        var newRow = document.createElement('tr');
        newRow.id = "pro_action_" + selectAction;
			
        if (selectAction == 1 || selectAction == 4) {
            var newTd1 = document.createElement('td');
            newTd1.height = 25;
            if (selectAction == 1) {
                newTd1.innerHTML = '<lable class="table_text">'+$('#cutPercent').val()+'</lable>';
            } else {
                newTd1.innerHTML = '<label class="table_text">Cut Second Percent</lable>';
            }
            var newTd2 = document.createElement('td');
            newTd2.innerHTML = '<input type="hidden" name="pro_action_type[]" value="' + selectAction + '" /><input type="text" size="10" name="pro_action_value[]" id="pro_action_value_' + selectAction + '" onblur="javascript:Promotion.validateNumber(\'#pro_action_value_' + selectAction + '\');" />%';
            var newTd3 = document.createElement('td');
            newTd3.innerHTML = '<span class="form_element_error" id="pro_action_value_' + selectAction + '_error"></span>';
			
            newRow.appendChild(newTd1);
            newRow.appendChild(newTd2);
            newRow.appendChild(newTd3);
        } else if (selectAction == 2 || selectAction == 5) {
            var newTd1 = document.createElement('td');
            newTd1.height = 25;
            if (selectAction == 2) {
                newTd1.innerHTML = '<label class="table_text">'+$('#cutAmount').val()+'</lable>';
            } else {
                newTd1.innerHTML = '<label class="table_text">Cut Second Amount</label>';
            }
	
            var newTd2 = document.createElement('td');
            newTd2.innerHTML = '<input type="hidden" name="pro_action_type[]" value="' + selectAction + '" /><input type="text" size="10" name="pro_action_value[]" id="pro_action_value_' + selectAction + '" onblur="javascript:Promotion.validateNumber(\'#pro_action_value_' + selectAction + '\');"/>';
            var newTd3 = document.createElement('td');
            newTd3.innerHTML = '<span class="form_element_error" id="pro_action_value_' + selectAction + '_error"></span>';
            newRow.appendChild(newTd1);
            newRow.appendChild(newTd2);
            newRow.appendChild(newTd3);
        } else if (selectAction == 3) {
            var newTd1 = document.createElement('td');
            newTd1.height = 25;
            newTd1.innerHTML = '<label class="table_text">'+$('#freeShipping').val()+'</label>';
            var newTd2 = document.createElement('td');
            newTd2.innerHTML = '<input type="hidden" name="pro_action_type[]" value="3" /><input type="hidden" name="pro_action_value[]" value="0" /><div class="button"></div>';
            newRow.appendChild(newTd1);
            newRow.appendChild(newTd2);
        }
        $("#actions_tbody").append(newRow);
        $('#action_show_error').empty();
    },
    removeAction:function(id) {
        //$('#actions_tbody').removeChild($('#'+id));
        $('#'+id).remove();
    },
    submitPromotion:function() {
        var selectId = tree.getAllChecked();
        if(selectId == ""){
            alert("Please select categories for product.");
            return;
        }else if(selectId == "-1"){
            alert("Please don't select 'Root' for product.");
            return;
        }
        $("#categoryId").val(selectId);
        Common.submit();
    },
    changeAction:function(){
        $('#actions_tbody').empty();
    },
    validateBlank:function(node){
        var v = $.trim($(node).val());
        var errId = node + "_error";
        if(ValidationUtil.isBlank(v)){
            ValidationUtil.showErrMsg(errId,$('#blank_error').val());
            return true;
        }else{
            ValidationUtil.clearErrMsg(errId);
        }
        return false;
    },
    validationSameName:function(node,type){
        var val = $(node).val();
        var id ="";
        var baseUrl = $('#baseurl').val();
        if($('#promotionid')!=null){
            id  = $('#promotionid').val();
        }
        var errId = node + "_error";
        var url = baseUrl + "/promotion/promotion/validationsame";
        $.ajax({
            type:"POST",
            async:false,
            url:url,
            data: {
                'name':val,
                'id':id,
                'type':type
            },
            dataType:"jason",
            success:function(responseText){
                if(responseText == "true"){
                    ValidationUtil.showErrMsg(errId,$('#same_error').val());
                    return true;
                }else{
                    ValidationUtil.clearErrMsg(errId);
                    return false;
                }
            }
        });
    },
    validationName:function(node,type){
        if(this.validateBlank(node)){
            return true;
        }else if(this.validationSameName(node,type)){
            return true;
        }else{
            return false;
        }
    },
    validationShortDescription:function(node){
        var errId = node + "_error";
        var showinproduct = $('#show_in_product').val();
        if(showinproduct==1){
            if(this.validateBlank(node)){
                return true;
            }else{
                ValidationUtil.clearErrMsg(errId);
                return false;
            }
        }
    },
    changeShowProduct:function(){
        $('#short_description_error').empty();
    },
    validateDate:function(node){
        var v = $.trim($(node).val());
        var errId = node + "_error";
        if(ValidationUtil.isDate(v)){

            ValidationUtil.showErrMsg(errId,$('#date_error').val());
            return true;
        }else{
            ValidationUtil.clearErrMsg(errId);
        }
        return false;
    },
    validationProDate:function(node){
        if(this.validateBlank(node)){
            return true;
        }else if(this.validateDate(node)){
            return true;
        }else{
            return false;
        }
    },
    validateNumber:function(node){
        var v = $.trim($(node).val());
        var errId = node + "_error";
        if(ValidationUtil.isNumber(v)){
            ValidationUtil.showErrMsg(errId,$('#number_error').val());
            return true;
        }else{
            ValidationUtil.clearErrMsg(errId);
        }
        return false;
    },
    savePromotion:function(){
        var result = false;
        var promotiontype = $('#promotiontype').val();
      //  var codeRes = $('#restriction_7').css('display');
      
        if(this.validationPromotionBase(promotiontype)){
            result = true;
        }
        if(this.validationPromotionRestriction()){
            result = true;
        }
        if(this.validateProAction()){
            result = true;
        }
    
     //Code Process and Validation
        $('#couponCodeError').text('');
        var codes = $("input[name='select_code']");
        var selectCodes = '';
        var trObj = '';
        var inputObj = '';
        
        var noCodeValid = true;
        var codeNo = 1;
        var codeVal = '';
        $.each(codes,function(i,obj){
        	codeNo = $(obj).val();
        	codeVal = $('#code_input_'+codeNo).val();
        	if(codeVal){
        		noCodeValid = false;
        	}
        	
        	selectCodes += $(obj).val()+',';
        	trObj = $(obj).parent().parent();
        	inputObj = $(trObj).children().eq(1).children().eq(0);
        	$inputCode = $.trim($(inputObj).val());
        		
        	if($inputCode!="" && !Promotion.checkCodeUnique(inputObj)){
        		result = true; 
        	}
        		
        });
        selectCodes = $.trim(selectCodes);
        selectCodes = selectCodes.substring(0,selectCodes.length-1);
        $('#select_code_num').val(selectCodes);
        
        if(noCodeValid){
        	$('#couponCodeError').text($('#noCouponCodeInfo').val());
        	result = true; 
        }
        
        
        if(result){
            return;
        }
        
        if($('#restriction_6').css("display")!='none'){
        	$('#customerRestriction').val(1);
        } else {
        	$('#customerRestriction').val(0);
        }
        //product promotion
        if(promotiontype == 2){
            //product restriction
            $("#productItemId").val(this.getProductItems());
            //category restriction
            $("#categoryId").val(this.getCategories());
        }
        //order promotion
        if(promotiontype == 3){
            if($('#restriction_3').css("display")!='none'){
                $("#selectedRestrictionType").val(3);
            }
        }
        
    //customer certf restriction 
        var certfRes = $('#restriction_8').css('display');
        if(certfRes != 'none'){
        	 var certfs = $("input[name='certf']");
        	 var certfStr = "";
        	 $(certfs).each(function(n,obj){
       		    if($(obj).attr("checked") == true){
       			    if(certfStr){
       				    certfStr += ','+$(obj).val();
       			    } else {
       				    certfStr = $(obj).val();
       			    }
       		    }
       	    });
        	 
        	$('#selectedCustomerCerfts').val(certfStr); 
        }
   //customer rank restriction
        var rankRes = $('#restriction_9').css('display');
        if(rankRes != 'none'){
        	 var ranks = $("input[name='rank']");
        	 var rankStr = "";
        	 $(ranks).each(function(n,obj){
       		    if($(obj).attr("checked") == true){
       			    if(rankStr){
       			    	rankStr += ','+$(obj).val();
       			    } else {
       			    	rankStr = $(obj).val();
       			    }
       		    }
       	    });
        	 
        	$('#selectedCustomerRanks').val(rankStr); 
        }
       
        Common.submit();
    },
    validationPromotionBase:function(promotiontype){
        var result = false;
        if(this.validationName('#name',1)){
            result = true;
        }
        if(this.validationShortDescription('#short_description')){
            result = true;
        }
        if(this.validateBlank('#long_description')){
            result = true;
        }
       
       // if(this.validationName('#code',2)){
       //     result = true;
      //  }
        
        if(!this.validInteger($.trim($('#uses_per_customer').val()),'uses_per_customer')){
            result = true;
        }
        
        if(!this.validInteger($.trim($('#uses').val()),'uses')){
            result = true;
        }
        
       
        if(this.validateBlank('#from')){
            result = true;
        }
        if(this.validateBlank('#to')){
            result = true;
        }
        
        if(promotiontype == 3 && $('#point_exchange').attr("checked") == true){
        	var exhaustPoint = $('#exhaust_point').val();
        	if(!this.validInteger(exhaustPoint,'exhaust_point')){
                result = true;
            }
        	var minACPoint = $('#min_ac_point').val();
        	if(!this.validInteger(minACPoint,'min_ac_point')){
                result = true;
            }
        	var startDate = $('#start_date').val();
        	if(!this.validEmpty(startDate,'start_date')){
                result = true;
            }
        	var endDate = $('#end_date').val();
        	if(!this.validEmpty(endDate,'end_date')){
                result = true;
            }
        }
        
        return result;
    },
    validationPromotionRestriction:function(){
        var promotiontype = $('#promotiontype').val();
        var result = false;
        var error = $('#condition_error').val();
        if(promotiontype ==2){
//            if($('#restriction_1').css("display")=='none' && $('#restriction_2').css("display")=='none'){
//                $('#Restriction_error').html(error);
//                result = true;
//            }else{
//                $('#Restriction_error').empty();
//            }
        }else if(promotiontype ==3){
          //  if($('#restriction_3').css("display")=='none' && $('#restriction_7').css("display")=='none'){
          //      $('#Restriction_error').html(error);
          //      result = true;
          //  }else 
            if ($('#restriction_3').css("display")!='none') {
                $('#Restriction_error').empty();
                if(this.validateNumber('#total')){
                    result = true;
                }
            }
        }
        return result;
    },
    validateProAction:function(){
        var promotiontype = $('#promotiontype').val();
        var result = false;
        var error = $('#action_error').val();
        if($('#actions_tbody').html()==""){
            $('#action_show_error').html(error);
            result = true;
        }else{
            $('#action_show_error').empty();
            var actiontype = $('#selectAction').val();
            if(actiontype!=3){
                var actionname = '#pro_action_value_'+actiontype;
                if(this.validateNumber(actionname)){
                    result = true;
                }
            }
        }
		
        return result;
    },
    openSearchDialog: function(baseUrl){
        var url = baseUrl + "/inventory/product/searchitem/from/promotion";
        Common.showDialog({
            url : url ,
            height : 450 ,
            width : 930 ,
            dataDiv : "searchDialog"
        });
    },
    searchItem: function(items){
        var trHtml = "";
        if(items){
            var selectedItems = $("input[name='itemCkb']");
            $(items).each(function(n,obj){
                var result = true;
                //check if has exist
                $(selectedItems).each(function(n,obj2){
                    if(obj.id == $(obj2).val()){
                        result = false;
                    }
                });
                if(result){
                    trHtml += "<tr id='itemRow" + obj.id + "'>";
                    trHtml += "<td class='dbgrid_td_ckb'>";
                    trHtml += "<input type='hidden' name='itemIds[]' value='"+ obj.id +"' /><input type='checkbox' style='margin-right:0px;' name='itemCkb' value='"+ obj.id +"' />";
                    trHtml += "</td>";
                    trHtml += "<td class='dbgrid_td'>";
                    trHtml += "<span>"+ obj.title +"</span>";
                    trHtml += "</td>";
                    trHtml += "<td class='dbgrid_td'>";
                    trHtml += "<span>"+ obj.sku +"</span>";
                    trHtml += "</td>";
                    trHtml += "<td class='dbgrid_td'>";
                    trHtml += "<span>"+ obj.upc +"</span>";
                    trHtml += "</td>";
                    trHtml += "<td class='dbgrid_td'>";
                    trHtml += "<span>";
                    if(obj.attribute_1 && obj.value_1){
                        trHtml += obj.attribute_1 + ":" + obj.value_1 + "<br/>";
                    }
                    if(obj.attribute_2 && obj.value_2){
                        trHtml += obj.attribute_2 + ":" + obj.value_2 + "<br/>";
                    }
                    if(obj.attribute_3 && obj.value_3){
                        trHtml += obj.attribute_3 + ":" + obj.value_3 + "<br/>";
                    }
                    if(obj.attribute_4 && obj.value_4){
                        trHtml += obj.attribute_4 + ":" + obj.value_4 + "<br/>";
                    }
                    if(obj.attribute_5 && obj.value_5){
                        trHtml += obj.attribute_5 + ":" + obj.value_4 + "<br/>";
                    }
                    trHtml += "<span>";
                    trHtml += "</span>";
                    trHtml += "</td>";
                    trHtml += "</tr>";
                }
            });
        }
        $("#productItemBody").append(trHtml);
        Common.closeDialog("searchDialog");
    },

    checkAll: function(){
        var status = $("#itemAllCkb").attr("checked");
        var items = $("input[name='itemCkb']");
        $.each(items,function(i,obj){
            $(obj).attr("checked",status);
        });
    },

    removeItems: function(){
        var items = $("input[name='itemCkb']");
        $.each(items,function(i,obj){
            if($(obj).attr("checked") == true){
                $("#itemRow" + $(obj).val()).remove();
            }
        });
        $("#itemAllCkb").attr("checked","");
    },

    getProductItems: function(){
        itemsCheck = new Array();
        if($('#restriction_1').css("display")!= 'none'){
            var items = $("input[name='itemCkb']");
            $.each(items,function(i,obj){
                itemsCheck.push($(obj).val());
            });
            return itemsCheck.join(",");
        }else{
            return "";
        }
    },

    getCategories: function(){
        if($('#restriction_2').css("display")!= 'none'){
            var selectId = tree.getAllChecked();
            return selectId;
        }else{
            return "";
        }
    },
    
    addNewCode : function(baseUrl){
    	var couponCode = this.getCouponCode(baseUrl);
    	
    	var removeBtn = $('#removeBtn').val();
    	var codeNum = eval($('#code_num').val())+1;
    	var html = "<tr><td class='dbgrid_td_ckb' ><input type='checkbox' id='select_code"+codeNum+"' name='select_code' value='"+codeNum+"' /></td>";
    	html += "<td class='dbgrid_td'><input type='text' id='code_input_"+codeNum+"' name='code_"+codeNum+"' value='"+couponCode+"' onblur='javascript:Promotion.checkCodeUnique(this);' /><div id='error_code_input_"+codeNum+"' class='form_element_error' /></div> </td>";
    	html += "<td class='dbgrid_td'><input type='text' style='width:80px;' id='customerid_input_"+codeNum+"' name='customerid_"+codeNum+"' /></td>";
    	html += "<td class='dbgrid_td'><input type='button' id='button_"+codeNum+"' value='"+removeBtn+"' onclick='javascript:Promotion.removeCode(this)' /></td></tr>";
    	$('#code_table').append(html);
    	$('#code_num').val(codeNum);
    	
    },
    
    removeCode : function(obj){
    	id = (obj).id;
    	var removeObj = $('#'+id).parent().parent();
    	
    	$(removeObj).remove();
    },
    
    removeSelectedCode : function(){
    	var codes = $("input[name='select_code']");
    	var removeObj = '';
    	$.each(codes,function(i,obj){
    		if($(obj).attr("checked") == true){
    			removeObj = $(obj).parent().parent();
    			$(removeObj).remove();
    		}
    	});
    },
    
    selectAllCode : function(obj){
    	var codes = $("input[name='select_code']");
    	$.each(codes,function(i,obj1){
    		$(obj1).attr("checked",$(obj).attr("checked"));
    	
    	});	
    },
    
    checkCodeUnique : function(obj){
    	var id = (obj).id;
    	var code = $.trim($(obj).val());
    	var result = true;
    	
    	var promotionId = $('#promotionid').val();
    	var data = '';
    	if(promotionId >0){
    		data = {"code" : code, "promotion_id" : promotionId};
    	} else {
    		data = {"code" : code};
    	}
    	var baseUrl = $('#baseurl').val();
    	$.ajax({
            type: 'post', 
            url: baseUrl+'/promotion/promotion/checkcodeunique', 
            data: data , 
            async: false,  //false is synchronization , true is asynchronism
            dataType : 'json',
            success: function(data){ 
    		   if(data == 1){
            		var codeExitInfo = "'"+code+"' "+$('#codeExitInfo').val();
            		$('#error_'+id).text(codeExitInfo);
            		result = false;
            	} else{
            		$('#error_'+id).text('');
            		result = true;
            	}
              
            }
             
         });
    	return result;
    },
    
    pointExchange : function(){
    	if($('#point_exchange').attr("checked") == true){
    		$('#pointExchangeInfo').slideDown('slow');
    		$('#point_exchange_select').val(1);
    	} else {
    		$('#pointExchangeInfo').slideUp('slow');
    		$('#point_exchange_select').val(0);
    	}
    },
    
    validEmpty : function(value,label){
    	$('#'+label+'Error').html('');
        if(ValidationUtil.isBlank(value)){
            var emptyErr = $('#blank_error').val();
            $('#'+label+'Error').css({"margin-left":"124px","margin-bottom":"5px"});
            $('#'+label+'Error').text(emptyErr);
            return false;
        } 
            return true;
    },
    
    validInteger : function(value,label){
    	if(!this.validEmpty(value, label)){
    		return false;
    	}
        if(!ValidationUtil.isInteger(value) && value!=0){
            var errInfo = $('#number_error').val();
            $('#'+label+'Error').css({"margin-left":"124px","margin-bottom":"5px"});
            $('#'+label+'Error').text(errInfo);
            return false;
        } 
            return true;
    	
    },
    
    openCustomerDialog: function(baseUrl){
    	var url = baseUrl + "/customer/customer/searchcustomer/from/promotion";
    	Common.showDialog({
            url : url ,
            height : 450 ,
            width : 930 ,
            dataDiv : "searchDialog"
        });
    },
    
    searchCustomer : function(items){
    	var trHtml = "";
    	if(items){
    		 var selectedItems = $("input[name='customerCkb']");
             $(items).each(function(n,obj){
                 var result = true;
                 //check if has exist
                 $(selectedItems).each(function(n,obj2){
                     if(obj.id == $(obj2).val()){
                         result = false;
                     }
                 });
                 
                 if(result){
                     trHtml += "<tr id='itemRow" + obj.id + "'>";
                     trHtml += "<td class='dbgrid_td_ckb'>";
                     trHtml += "<input type='hidden' name='customerIds[]' value='"+ obj.id +"' /><input type='checkbox' style='margin-right:0px;' name='customerCkb' value='"+ obj.id +"' />";
                     trHtml += "</td>";
                     trHtml += "<td class='dbgrid_td'>";
                     trHtml += "<span>"+ obj.user_num +"</span>";
                     trHtml += "</td>";
                     trHtml += "<td class='dbgrid_td'>";
                     trHtml += "<span>"+ obj.name +"</span>";
                     trHtml += "</td>";
                     trHtml += "<td class='dbgrid_td'>";
                     trHtml += "<span>"+ obj.email +"</span>";
                     trHtml += "</td>";
                     trHtml += "</tr>";
                 }
                 
             });
    		
    	} 
    	$("#customerBody").append(trHtml);
        Common.closeDialog("searchDialog");
    },
    
    checkCustomerAll: function(){
        var status = $("#customerAllCkb").attr("checked");
        var customers = $("input[name='customerCkb']");
        $.each(customers,function(i,obj){
            $(obj).attr("checked",status);
        });
    },
    
    removeCustomers: function(){
        var customers = $("input[name='customerCkb']");
        $.each(customers,function(i,obj){
            if($(obj).attr("checked") == true){
                $("#itemRow" + $(obj).val()).remove();
            }
        });
        $("#customerAllCkb").attr("checked","");
    },
    
    getCouponCode : function(baseUrl){
    	var code = '';
    	$.ajax({
            type: 'post', 
            url: baseUrl+'/promotion/promotion/getcouponcode', 
            async: false,  //false is synchronization , true is asynchronism
            dataType : 'json',
            success: function(data){
    		    code = data;
            }
             
         });
    	
    	return code;
    }
}